package com.ruoyi.web.controller.vivo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.UUID;

/**
 * VivoApiUtil -
 * Created by Jack on 2025/7/31.
 * Description:
 */
@Service
public class VivoApiUtil {


    /***
     *  vivo openapi 请求地址
     * */
    private static final String VIVO_OPENAPI_URL = "https://marketing-api.vivo.com.cn/openapi";


    public String post(String url,String advertiserId, String accessToken,String jsonStr) throws IOException {
        String nonce = UUID.randomUUID().toString().replace("-", "");
        String timestamp =String.valueOf(System.currentTimeMillis());
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonStr);
        Request request = new Request.Builder()
                .url(VIVO_OPENAPI_URL+url + "?access_token=" + accessToken + "&timestamp=" + timestamp + "&nonce=" + nonce + "&advertiser_id=" + advertiserId)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public String getAdvertiseQualificationId(JSONObject request, String category) {
        // 解析category参数
        String[] categoryParts = category.split("-");
        if (categoryParts.length != 3) {
            return "";
        }
        String industry1Name = categoryParts[0];
        String industry2Name = categoryParts[1];
        String productName = categoryParts[2];
        try {
            // 获取data数组
            JSONArray dataArray = request.getJSONArray("data");

            // 遍历data数组
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject industryObj = dataArray.getJSONObject(i);

                // 检查industry1Name和industry2Name是否匹配
                if (industry1Name.equals(industryObj.getString("industry1Name")) &&
                        industry2Name.equals(industryObj.getString("industry2Name"))) {

                    // 获取广告资质列表
                    JSONArray qualificationList = industryObj.getJSONArray("advertiseQualificationList");

                    // 遍历资质列表查找匹配productName的项
                    for (int j = 0; j < qualificationList.size(); j++) {
                        JSONObject qualification = qualificationList.getJSONObject(j);
                        if (productName.equals(qualification.getString("productName"))) {
                            return qualification.getString("advertiseQualificationId");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未找到对应资质";
    }

    /**
     * 从JSONArray中查找指定name对应的id
     * @param jsonArray 数据数组 (包含多个广告计划对象)
     * @param targetName 要查找的计划名称
     * @return 匹配的id (long类型)，未找到返回null
     */
    public  Long findIdByName(JSONArray jsonArray, String targetName) {
        if (jsonArray == null || targetName == null) {
            return null;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            if (item != null && targetName.equals(item.getString("name"))) {
                return item.getLong("id");
            }
        }
        return null;
    }
}
